package cn.itcast.haoke.im.websocket;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

/**
 * @Author: JLL
 * @Date: 2020/7/18 14:49
 */

@Component
public class MessageHandshakeInterceptor implements HandshakeInterceptor {

    /**
     * 握手之前， 也就是建立连接之前，需要做的事。
     * 客户端连上去的时候，是通过： ws://127.0.0.1:10081/ws/{uid}
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request,
                                   ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler,
                                   Map<String, Object> attributes) throws Exception {
        String path = request.getURI().getPath();
        String[] ss = StringUtils.split(path, '/');
        if(ss.length != 2){
            return false;  //拒绝握手，
        }
        if(!StringUtils.isNumeric(ss[1])){ //是否为数字。。 不是也拒绝握手。。因为全局的map的key是long类型
            return false;
        }
        attributes.put("uid", Long.valueOf(ss[1]));
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {

    }
}
